using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PasteFormHelper;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;

namespace OpenPasteSpider.bind
{

    /// <summary>
    /// 模块运行在哪些服务器上
    ///</summary>
    [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
    public class BindModelLinuxAppService : OpenPasteSpiderAppService
    {

        private readonly ChannelHelper _channelHelper;
        private IOpenPasteSpiderDbContext _dbContext;
        public BindModelLinuxAppService(IOpenPasteSpiderDbContext dbContext, ChannelHelper channelHelper)
        {
            _dbContext = dbContext;
            _channelHelper = channelHelper;
        }
        /// <summary>
        /// 按页获取模块运行在哪些服务器上
        ///</summary>
        /// <param name="page"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PagedResultDto<BindModelLinuxListDto>> GetListAsync(int page = 1, int size = 20)
        {

            var query = _dbContext.BindModelLinux.Where(t => 1 == 1)
            .OrderByDescending(xy => xy.Id);

            var pagedResultDto = new PagedResultDto<BindModelLinuxListDto>();
            pagedResultDto.TotalCount = await query.CountAsync();
            var userList = await query.Page(page, size).ToListAsync();
            var temList = ObjectMapper.Map<List<BindModelLinux>, List<BindModelLinuxListDto>>(userList);
            pagedResultDto.Items = temList;
            return pagedResultDto;
        }

        /// <summary>
        /// 根据ID获取单项模块运行在哪些服务器上
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public BindModelLinuxDto GetByIdAsync(int id)
        {
            var query = _dbContext.BindModelLinux.Where(t => t.Id == id)
            .FirstOrDefault();
            var temList = ObjectMapper.Map<BindModelLinux, BindModelLinuxDto>(query);
            return temList;
        }

        /// <summary>
        /// 根据ID获取待更新单项信息模块运行在哪些服务器上
        ///</summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public BindModelLinuxUpdateDto GetInfoForUpdateAsync(int id)
        {
            var query = _dbContext.BindModelLinux.Where(t => t.Id == id)
            .FirstOrDefault();
            var temList = ObjectMapper.Map<BindModelLinux, BindModelLinuxUpdateDto>(query);
            return temList;
        }


        /// <summary>
        /// 添加一个模块运行在哪些服务器上
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BindModelLinuxDto> CreateItemAsync(BindModelLinuxAddDto input)
        {
            var model = _dbContext.ModelInfo.Where(x => x.Id == input.ModelId).Include(x => x.Service).AsNoTracking().FirstOrDefault();
            if (model == null || model == default)
            {
                throw new PasteCodeException("环境信息没有找打，请重试");
            }

            var newu = ObjectMapper.Map<BindModelLinuxAddDto, BindModelLinux>(input);
            newu.IsEnable = true;            //添加自定义
            newu.ModelCode = model.Code;
            newu.ServiceId = model.Service.Id;

            _dbContext.Add(newu);
            await _dbContext.SaveChangesAsync();
            //var updated = await _repository.InsertAsync(newu,true);
            var backinfo = ObjectMapper.Map<BindModelLinux, BindModelLinuxDto>(newu);

            _channelHelper.WriteMonitor(new ChannelMonitorModel() { BoolMonitor = false, LinuxId = input.LinuxId, ModelCode = "", ServiceId = 0 });

            return backinfo;
        }
        /// <summary>
        /// 更新一个模块运行在哪些服务器上
        ///</summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<BindModelLinuxDto> UpdateItemAsync(BindModelLinuxUpdateDto input)
        {
            var info = await _dbContext.BindModelLinux.Where(x => x.Id == input.Id).FirstOrDefaultAsync();
            if (info == null || info == default)
            {
                throw new UserFriendlyException("需要查询的信息不存在", "404");
            }

            if (info.ModelId != input.ModelId)
            {
                var model = _dbContext.ModelInfo.Where(x => x.Id == input.ModelId).Include(x => x.Service).AsNoTracking().FirstOrDefault();
                if (model == null || model == default)
                {
                    throw new PasteCodeException("环境信息没有找打，请重试");
                }
                info.ModelCode = model.Code;
                info.ServiceId = model.Service.Id;
            }

            ObjectMapper.Map<BindModelLinuxUpdateDto, BindModelLinux>(input, info);
            //var updated = await _repository.UpdateAsync(newu);
            await _dbContext.SaveChangesAsync();
            var backinfo = ObjectMapper.Map<BindModelLinux, BindModelLinuxDto>(info);

            _channelHelper.WriteMonitor(new ChannelMonitorModel() { BoolMonitor = false, LinuxId = input.LinuxId, ModelCode = "", ServiceId = 0 });

            return backinfo;
        }
        
        /// <summary>
        /// 读取AddDto的数据模型 用于新增
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadAddModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<BindModelLinuxAddDto>(new BindModelLinuxAddDto());
            return _model;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于更新
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadUpdateModel(int id)
        {
            var _info = await _dbContext.BindModelLinux.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<BindModelLinux, BindModelLinuxUpdateDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<BindModelLinuxUpdateDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取Dto的数据模型 用于查看详情
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<VoloModelInfo> ReadDetailModel(int id)
        {
            var _info = await _dbContext.BindModelLinux.Where(x => x.Id == id).AsNoTracking().FirstOrDefaultAsync();
            if (_info == null || _info == default)
            {
                throw new PasteCodeException("查询的信息不存在，无法执行编辑操作！");
            }
            var dto = ObjectMapper.Map<BindModelLinux, BindModelLinuxDto>(_info);
            var _dataModel = PasteBuilderHelper.ReadModelProperty<BindModelLinuxDto>(dto);
            return _dataModel;
        }

        /// <summary>
        /// 读取ListDto的数据模型
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public VoloModelInfo ReadListModel()
        {
            var _model = PasteBuilderHelper.ReadModelProperty<BindModelLinuxListDto>(new BindModelLinuxListDto());
            var _query_model = PasteBuilderHelper.ReadModelProperty(new InputSearchBase());
            if (_query_model != null)
            {
                _model.QueryProperties = _query_model.Properties;
            }
            return _model;
        }

        /// <summary>
        /// 按页获取数据
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        [TypeFilter(typeof(RoleAttribute), Arguments = new object[] { "data", "view" })]
        public async Task<PagedResultDto<BindModelLinuxListDto>> Page([FromQuery]InputSearchBase input)
        {
            var query = _dbContext.BindModelLinux.Where(t => 1 == 1).OrderByDescending(x=>x.Id);
            var _pagedto = new PagedResultDto<BindModelLinuxListDto>();
            _pagedto.TotalCount = await query.CountAsync();
            var userList = await query.Page(input.page, input.size).ToListAsync();
            var temList = ObjectMapper.Map<List<BindModelLinux>, List<BindModelLinuxListDto>>(userList);
            _pagedto.Items = temList;
            return _pagedto;
        }    }
}
